import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path:"/",
    redirect:"/home",
    meta:{
      show:true
    }
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    meta:{
      show:true
    },
    children:[
    {
      path:'search',
      name:'search',
      component:function () {
        return import(/* webpackChunkName: "search" */ '../views/search.vue')
      },
      meta:{
        show:false
      }
    }
    ]
  },
  {
    path: '/topic',
    name: 'topic',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: function () {
      return import(/* webpackChunkName: "topic" */ '../views/topic.vue')
    },
    meta:{
      show:true
    }
  },
  {
    path: '/category',
    name: 'category',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: function () {
      return import(/* webpackChunkName: "category" */ '../views/category.vue')
    },
    meta:{
      show:true
    }
  },

  {
    path: '/cart',
    name: 'cart',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: function () {
      return import(/* webpackChunkName: "cart" */ '../views/cart.vue')
    },
    meta:{
      show:true
    }
  },
  {
    path: '/user',
    name: 'user',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: function () {
      return import(/* webpackChunkName: "user" */ '../views/user.vue')
    },
    meta:{
      show:true
    }
  },
  {
    path: '/productDetail/?id=:id',
    name: 'productDetail',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: function () {
      return import(/* webpackChunkName: "productDetail" */ '../views/productDetail.vue')
    },
    meta:{
      show:false
    }
  },
]

const router = new VueRouter({
  routes
})
// 前置路由守卫
router.beforeEach ((to, from, next) => {
  let token = localStorage.getItem ('token')
  if (to.path == '/cart') {
    // 判断是否登录，是否有token
    if (token) {
      next ()
    } else {
      Vue.prototype.$toast ('请先登录')
      setTimeout (() => {
        next ('/user')
      }, 1000)
    }
  }
  // 让页面回到顶部
     document.documentElement.scrollTop = 0
 
  next ()
})
export default router
